package com.yxx.strategy.uploadStrategyImpl;

import com.aliyun.oss.*;
import com.yxx.config.properties.OssProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;

/**
 * oss上传策略实现
 * @author yuxiangxun
 * @date 2025/1/27
 * @apiNote
 */
@Slf4j
@Service("ossUploadStrategyImpl")
public class OssUploadStrategyImpl extends AbstractUploadStrategyImpl{

    @Resource
    private OssProperties ossProperties;


    /**
     * 判断文件是否存在
     * @param filePath 文件路径
     * @return
     */
    @Override
    public Boolean exists(String filePath) {
        return getOssClient().doesObjectExist(ossProperties.getBucketName(), filePath);
    }


    /**
     * 上传
     * @param path        路径
     * @param fileName    文件名
     * @param inputStream 输入流
     * @throws IOException
     */
    @Override
    public void upload(String path, String fileName, InputStream inputStream) throws IOException {
        // 获取oss客户端
        OSS ossClient = getOssClient();
        try{
            // 调用 oss 方法上传
            ossClient.putObject(ossProperties.getBucketName(), path + fileName, inputStream);
        }catch (OSSException oe){
            log.error("Error Message:" + oe.getErrorMessage());
            log.error("Error Code:" + oe.getErrorCode());
            log.error("Request ID:" + oe.getRequestId());
            log.error("Host ID:" + oe.getHostId());
        }catch (ClientException ce){
            log.error("Caught an ClientException, Error Message:" + ce.getMessage());
        }finally{
            if(ossClient != null){
                ossClient.shutdown();
            }
        }
    }

    /**
     * 获取文件访问url
     * @param filePath 文件路径
     * @return
     */
    @Override
    public String getFileAccessUrl(String filePath) {
        return ossProperties.getUrl() + filePath;
    }

    /**
     * 获取oss客户端
     * @return
     */
    private OSS getOssClient() {
        return new OSSClientBuilder().build(
                ossProperties.getEndpoint(),
                ossProperties.getAccessKeyId(),
                ossProperties.getAccessKeySecret()
        );
    }
}
